package cn.com.bsoft.cloud.controller.healthweb;

import cn.com.bsoft.cloud.service.CloudHealthService;
import cn.com.bsoft.cloud.utils.FileUtils;
import cn.com.bsoft.cloud.utils.ResultCode;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.*;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/cloudhealth/")
public class HealthWebController {


    public static Logger logger = LogManager.getLogger(HealthWebController.class);

    @Autowired
    private CloudHealthService cloudHealthService;


    /**
     * 此人三个月内是否有过就诊
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("queryExistMess")
    public Map<String, Object> queryExistMess(@RequestBody Map<String, String> map) {
        Map<String, Object> regMsg = new HashMap<String, Object>();

        try {
            String cardNo = map.get("cardNo");
            String hosCode = map.get("hosCode");
            if (StringUtils.isBlank(cardNo)) {
                regMsg.put("code", ResultCode.PARAMETERS_EMPTY);
                regMsg.put("msg", "卡号不能为空");
                return regMsg;
            }
            if (StringUtils.isBlank(hosCode)) {
                regMsg.put("code", ResultCode.PARAMETERS_EMPTY);
                regMsg.put("msg", "医院编码不能为空");
                return regMsg;
            }
            /*List<String> listStr= cloudHealthService.queryExistMess(cardNo,hosCode);
            if(listStr!=null&&listStr.size()>0){
                regMsg.put("code", ResultCode.SUCCESS);
                regMsg.put("msg", "近三个月在此医院有就诊记录");
                regMsg.put("statu", "1");
            }else{
                regMsg.put("code", ResultCode.SUCCESS);
                regMsg.put("msg", "近三个月在此医院无就诊记录");
                regMsg.put("statu", "0");
            }*/
            regMsg.put("code", ResultCode.SUCCESS);
            regMsg.put("msg", "近三个月在此医院有就诊记录");
            regMsg.put("statu", "1");
        } catch (Exception e) {
            regMsg.put("code", ResultCode.ERROR);
            regMsg.put("msg", "请求出错");
            regMsg.put("error", e.getMessage());
            logger.error("查询近三个月是否有过就诊记录,参数:" + map + "，异常" + e.getMessage(), e);
        }
        return regMsg;
    }


    /**
     * 上传文件
     *
     * @return
     */
    @RequestMapping("uploadFile")
    @ResponseBody
    public Map<String, Object> singleFileUpload(@RequestParam("file") MultipartFile file,@RequestParam("yyid") String yyid,RedirectAttributes redirectAttributes) {

        Map<String, Object> map = new HashMap<String, Object>();

        if(file==null){
            map.put("code",ResultCode.PARAMETERS_EMPTY);
            map.put("msg","文件不能为空");
            return map;
        }
        if(StringUtils.isBlank(yyid)){
            map.put("code",ResultCode.PARAMETERS_EMPTY);
            map.put("msg","yyid不能为空");
            return map;
        }
        String key = "cdadf271070349e25ff3";

        BasicAWSCredentials credentials = new BasicAWSCredentials(key, "0cb562bd9bd57e76344ad8621ff7cb2238ce5c29");

        AmazonS3Client client = new AmazonS3Client(credentials);

        client.setEndpoint("http://oos-hq-sh.ctyunapi.cn");
        String bucketName = "mh-oos-bucket";
        try {
            String uuid = UUID.randomUUID().toString();
            String fileKey = key+uuid;
            File tmpFile =File.createTempFile("tmp","tmp");
            FileOutputStream output = new FileOutputStream(tmpFile);
            InputStream ins = file.getInputStream();
            tmpFile=new File(file.getOriginalFilename());
            FileUtils.inputStreamToFile(ins, tmpFile);
            ObjectMetadata metadata = new ObjectMetadata();

            metadata.setContentType("multipart/form-data");
            metadata.setContentLength(tmpFile.length());
            metadata.addUserMetadata("x-amz-meta-title", tmpFile.getName());
            metadata.setContentDisposition("attachment; filename="+tmpFile.getName());

            PutObjectRequest putRequest = new PutObjectRequest(bucketName, fileKey, new FileInputStream(tmpFile), metadata);
            client.putObject(putRequest);
            S3Object obj = client.getObject(new GetObjectRequest(bucketName, fileKey));
            URI uri = obj.getObjectContent().getHttpRequest().getURI();

            obj.getObjectContent().close();
            if(uri!=null){
                //添加文件地址与对应的yyid
//                Boolean bool=cloudHealthService.insertFileurl(yyid,uri);
//                if(bool){
                    map.put("code",ResultCode.SUCCESS);
                    map.put("msg","上传成功");
                    map.put("result",uri);
//                }else{
//                    map.put("code",ResultCode.ERROR);
//                    map.put("msg","上传失败(添加文件与预约关系)");
//                    map.put("result",null);
//                }

            }else{
                map.put("code",ResultCode.ERROR);
                map.put("msg","上传失败");
                map.put("result",null);
            }
        } catch (Exception e) {
            map.put("code",ResultCode.ERROR);
            map.put("msg",e.getMessage());
        }
        return map;
    }

}




